import React, {useState} from "react";
import {Button, Form, Modal, Spin} from "@douyinfe/semi-ui";
import { FormApi } from "@douyinfe/semi-ui/lib/es/form";
import { IconClose, IconTick, IconUpload, IconBolt } from '@douyinfe/semi-icons';
import {httpPost, Result} from "../../utils/http";
import {Error, Success} from "../../utils/message";

interface ServerAddProp {
    visible: boolean;
    closeModal: (isLoad: boolean) => void;
}

interface ServerFromProp {
    title: string;
    host: string;
    port: number;
    username: string;
    password: string;
    brief: string;
}

export const ServerAdd: React.FC<ServerAddProp> = ({visible, closeModal}) => {

    const [formApi, setFormApi] = useState<FormApi<ServerFromProp>>();

    const [spinning, setSpinning] = useState<boolean>(false);

    const handleAfterClose = () => formApi?.reset();

    const handleCancel = (isLoad: boolean) => {
        formApi?.reset();
        closeModal(isLoad);
    }

    const handleOk = (values: any) => {
        console.log("values", values);
        setSpinning(true);
        httpPost<Result<boolean>, any>('/server/add', values).then(res => {
            setSpinning(false);
            if (res.code === 200) {
                Success('增加成功');
                handleCancel(true);
            } else {
                Error(res.msg);
            }
        }).catch(err => {
            setSpinning(false);
            Error(err);
        })
    }


    return <Modal
        title="创建服务"
        visible={visible}
        maskClosable={false}
        onOk={handleOk}
        afterClose={handleAfterClose}
        onCancel={() => handleCancel(false)}
        closeOnEsc={true}
        footer={<>
            <Button type="danger" icon={<IconClose />} theme={'solid'} onClick={() => handleCancel(false)}>取消</Button>
            <Button type="primary" icon={<IconTick />} theme={'solid'} onClick={() => formApi?.submitForm()}>确认</Button>
        </>}
    >
        <Spin spinning={spinning} tip={'加载中......'}>
            <Form labelPosition={"left"} getFormApi={setFormApi} onSubmit={handleOk} labelCol={{span: 4}} wrapperCol={{span: 20}}>
                <Form.Input field='title' showClear label='名称' rules={[{required: true, message: '服务器名称未填写'}]}/>
                <Form.Input field='host' showClear label='地址' rules={[{required: true, message: '服务器地址未填写'}]}/>
                <Form.InputNumber field='port' label='端口' style={{width: '100%'}} initValue={22}/>
                <Form.Input field='username' showClear label='账号' rules={[{required: true, message: '服务器用户名未填写'}]}/>
                <Form.Input field='password' showClear mode={'password'} label='密码' rules={[{required: true, message: '服务器密码未填写'}]}/>
                <Form.TextArea maxCount={150} showClear field='brief' label='备注'  />
            </Form>
        </Spin>
    </Modal>
}